package cq.zhcqk.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dou361.dialogui.DialogUIUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

import org.apache.http.Header;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cq.zhcqk.MainActivity;
import cq.zhcqk.R;
import cq.zhcqk.util.AsyncHttpClientUtils;
import cq.zhcqk.util.Common;
import cq.zhcqk.util.GsonUtil;
import cq.zhcqk.util.ImageLoaderHelper;
import cq.zhcqk.util.ImeiHelper;
import cq.zhcqk.util.ImgDonwloads;
import cq.zhcqk.util.SharedPreferencesHelper;
import cq.zhcqk.util.SpUtil;
import cq.zhcqk.util.StringUtil;

/**
 * Created by zhangle on 2017/5/29.
 */
public class SplashActivity extends Activity {

    private Context context;

    private TextView timer_text;

    private int recLen = 4;

    private AsyncHttpClient httpClient;
    private ImageView start_img;
    private SharedPreferences mSharedPreferences;
    Timer timer = new Timer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        context = this;
        httpClient = AsyncHttpClientUtils.getInstance().getAsyncHttpClient();
        start_img = (ImageView) findViewById(R.id.start_img);
        intPage();
        timer_text = (TextView) findViewById(R.id.timer_text_tt);
//        timer.schedule(task, 1000,1000);
        countDownTimer.start();
        timer_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context,MainActivity.class));
                if (timer!=null) {
                    timer.cancel();
                    timer=null;
                }
                if (task!=null) {
                    task.cancel();
                    task=null;
                }
//                startActivity(new Intent(context,MainActivity.class));
                countDownTimer.cancel();
                timer_text.setText("正在启动..");
                finish();
            }
        });
        getStartInfo();
    }

    private void intPage(){
        Uri uri = Uri.fromFile(new File(Common.FILE_PAGE_PATH));
        if(uri != null){
            File f = new File(Common.FILE_PAGE_PATH);
            if(f.exists()){
                start_img.setImageURI(uri);
            }
        }
        mSharedPreferences = SpUtil.getSpBykey(context, SpUtil.START_PAGE);
        final String page = mSharedPreferences.getString("pageUrl",null);
        if(!StringUtil.isNull(page)){
            start_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context,StartPageActivity.class);
                    intent.putExtra("pageUrl",page);
                    startActivity(intent);
                    timer.cancel();
                    finish();
                }
            });
        }
    }

    //启动
    Handler handlerX = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 999) {
                timer_text.setText(recLen+" 秒后跳转");
                if(recLen <= 1){
                    if (timer!=null) {
                        timer.cancel();
                        timer=null;
                    }
                    if (task!=null) {
                        task.cancel();
                        task=null;
                    }
                    startActivity(new Intent(context,MainActivity.class));
                    finish();
                }
            }
            super.handleMessage(msg);
        }
    };

    TimerTask task = new TimerTask() {

        @Override
        public void run() {
            // 需要做的事:发送消息
            recLen--;
            Message message = new Message();
            message.what = 999;
            handlerX.sendMessage(message);
        }
    };

    CountDownTimer countDownTimer = new CountDownTimer(4*1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            timer_text.setText((millisUntilFinished / 1000)+" 秒后跳转");
            if((millisUntilFinished / 1000) == 1){
                timer_text.setText("正在启动..");
                startActivity(new Intent(context,MainActivity.class));
                finish();
            }
        }

        @Override
        public void onFinish() {
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        countDownTimer.cancel();
    }

    private void getStartInfo(){
        RequestParams params = new RequestParams();
        params.add("imei", ImeiHelper.getImei(context)+"");
        String url = "";
        url = Common.URL+Common.START;
        httpClient.post(url,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("启动页onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(StringUtil.stringToInt(map.get("code")+"") != 0 || map.get("data") == null){
//                    Toast.makeText(context,"获取支付信息失败，请稍后再试",Toast.LENGTH_SHORT).show();
                    return;
                }
                ImgDonwloads.donwloadImg(context,((Map<String, Object>)map.get("data")).get("url")+"");
                SharedPreferences.Editor editor = mSharedPreferences.edit();
                editor.putString("pageUrl",((Map<String, Object>)map.get("data")).get("openUrl")+"");
                editor.commit();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("启动页errorResponse："+errorResponse);
//                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("启动页responseString："+responseString);
//                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }
}
